import '@/style/login.less'
import md5 from './md5'
import _ from '@/common'
import Time from '@/common/time'
import env from '@/common/env'
;(function () {
  function getUrlParam (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) {
      return unescape(r[2])
    } else {
      return null
    }
  }
  var $ = (...arg) => document.querySelectorAll(...arg)
  if (!$('.form-login').length) {
    return
  }
  var $input = $('.btn-login')[0]
  var $error = $('.login-error')[0]
  var hasCard = false
  if (!hasCard) {
    $('.card-item')[0].style.display = 'none'
    $('.card')[0].removeAttribute('required')
    $('input[name=card]')[0].removeAttribute('name')
  }
  if (env.name) {
    $('.env-box')[0].innerHTML = env.name
    $('body')[0].classList.add('env')
  }
  var isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") >= 0;
  if (!isChrome) {
     $('.isChrome')[0].style.display = "block";
  }
  Array.prototype.forEach.call($('input'), (item) => item.addEventListener('input', () => {
    $error.innerHTML = null
  }))

  $('.form-login')[0].addEventListener('submit', (e) => {
    e.preventDefault()
    var name = _.trim($('input[class=name]')[0].value)
    var password = _.trim($('input[class=password]')[0].value)
    window.LinkErrorHandler = (res) => {
      loginError(res.buz_error_msg || '登录错误！')
    }
    let app = 'cs'
    var appMeta = document.querySelector('meta[name=APP_CODE]')
    if (appMeta) {
      app = appMeta.attributes.content.value
    }
    $input.innerHTML = '登录中...'
    $input.setAttribute('disabled', 'disabled')
    _.link(`/service/${app}/signin?name=${name}&password=${md5(name,password)}`, {
      method: 'get',
      retry: false
    }).then((res) => {
      var user = _.local('user') || {}
      user[app] = res.data
      _.local('user', user)
      if (window.location.href.indexOf('?') !== -1 && window.location.href.split('?')[1].indexOf('from') !== -1) {
        let query = getUrlParam('from').replace(/\%2F/g, '/')
        window.location.href = query + '?_=' + Date.parse(new Date())
      } else {
        window.location.href = '/?_=' + Date.parse(new Date())
      }
    }).finally(() => {
      $input.removeAttribute('disabled')
      $input.innerHTML = '登录'
    })
  })
  function loginError (text) {
    $error.innerHTML = text
    $input.removeAttribute('disabled')
    $input.innerHTML = '登录'
  }

  var buildTime = '00-00-00'
  var buildMeta = document.querySelector('meta[name=build]')
  if (buildMeta) {
    buildTime = Time.toTime(
      new Date(buildMeta.attributes.content.value)
    )
  }
  document.querySelector('.footer').innerHTML = `${window.App} @ ${buildTime}`
})()
